<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>计划管理</title>
    <script src="../../static/bootstrap5.0.1/bootstrap5/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="../../static/bootstrap5.0.1/bootstrap5/bootstrap.min.css">
    <link rel="stylesheet" href="../../static/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../../static/layuiadmin/style/admin.css" media="all">
    <script src="../../static/layuiadmin/layui/layui.js"></script>
    <link rel="stylesheet" href="../../static/css/common.css">
    <style>
        .bx {
            margin-left: 50px;
            margin-top: 50px;
        }

        .layui-table-cell {
            height: 40px;
            line-height: 40px;
        }

        .layui-input-block {
            margin-left: 150px;
            min-height: 36px;
        }
    </style>
</head>
<body>
<div class="layui-form">
    <div class="layui-inline tp">
        <div class="layui-form-item" style="margin-left: -110px;">
            <div class="layui-input-block">
                <input type="text" name="title" required lay-verify="required" placeholder="请输入计划名称"
                       autocomplete="off" class="layui-input" id="plan_name_search">
            </div>
        </div>
    </div>
    <!--    <div class="layui-inline">-->
    <!--        <label class="layui-form-label" style="width: auto;">日志创建时间</label>-->
    <!--        <div class="layui-input-inline">-->
    <!--            <input type="text" name="date" id="log_date_search" lay-verify="date" placeholder="yyyy-MM"-->
    <!--                   autocomplete="off"-->
    <!--                   class="layui-input">-->
    <!--        </div>-->
    <!--    </div>-->
    <div class="layui-inline tp1">
        <div class="layui-form-item">
            <button id="searchconfig" class="btn btn-primary">搜索</button>
            <button id="datainit" class="btn btn-danger">新增</button>
        </div>
    </div>
    <div id="show_table" lay-filter="show_table">
    </div>
</div>
<div id="addplan" style="display: none;">
    <div class="layui-form tp" style="margin-left: 50px;">
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: auto;">计划名称</label>
            <div class="layui-input-block" style="width: 250px;">
                <input type="text" id="plan_name" name="zc_name" lay-verify="required"
                       placeholder="请输入计划名称"
                       autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: auto;">计划类型</label>
            <div class="layui-input-block" style="width: 250px;">
                <select id="plan_type">
                    <option value="0">Multiple Max</option>
                    <option value="1">Single Max</option>
                    <option value="2">Dynamic Max</option>
                </select>
            </div>
            <div class="layui-form-item tp">
                <label class="layui-form-label" style="width: auto;">计划开始时间</label>
                <div class="layui-input-block" style="width: 250px;">
                    <input type="text" id="start_time" name="zc_name" lay-verify="required"
                           placeholder="请选择计划开始日期"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: auto;">计划结束时间</label>
                <div class="layui-input-block" style="width: 250px;">
                    <input type="text" id="end_time" name="zc_name" lay-verify="required"
                           placeholder="请选择计划结束日期"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>
        </div>
    </div>
</div>
<div style="display: none;" id="dynamic_execute">
    <div class="layui-form">
        <div class="layui-inline tp">
            <div class="layui-form-item" style="margin-left: -110px;">
                <div class="layui-input-block">
                    <input type="text" name="title" required lay-verify="required" placeholder="请输入型号"
                           autocomplete="off" class="layui-input" id="product_model_s">
                </div>
            </div>
        </div>
        <div class="layui-inline tp1">
            <div class="layui-form-item">
                <button id="product_search" class="btn btn-primary">搜索</button>
            </div>
        </div>
    </div>
    <div>
        <label for="product_search" style="color: red;margin-left: 50px;">注意：*型号执行的顺序是自己控制的，比如当前你选择了55A5D
            Pro
            并且执行了，那么该型号的执行顺序就是1，
            再执行其他型号事依次类推分批计数,
            如果一次性执行了多个型号，
            那么这几个型号在当前执行批次中并没有先后顺序*</label>
    </div>
    <div>
        <div class="layui-row" style="margin-left: 20px;">
            <div class="layui-col-xs4">
                <div id="bind_table" lay-filter="bind_table"></div>
            </div>
            <div class="layui-col-xs8">
                <div id="bind_execute_table" lay-filter="bind_execute_table">
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script type="text/html" id="operator">
    <!--    <button class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</button>-->
    <button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="execute">执行计划</button>
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
</script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-bg-cyan" lay-event="executeCheckData">执行选中的型号</button>
        <!--        <button class="layui-btn layui-btn-sm" lay-event="getData">获取当前页数据</button>-->
        <!--        <button class="layui-btn layui-btn-sm" id="dropdownButton">-->
        <!--            下拉按钮-->
        <!--            <i class="layui-icon layui-icon-down layui-font-12"></i>-->
        <!--        </button>-->
        <!--        <button class="layui-btn layui-btn-sm layui-bg-blue" id="reloadTest">-->
        <!--            重载测试-->
        <!--            <i class="layui-icon layui-icon-down layui-font-12"></i>-->
        <!--        </button>-->
    </div>
</script>
<script type="text/html" id="toolbarDemo1">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-bg-red" lay-event="export">导出执行结果</button>
    </div>
</script>
<script>
    layui.use(["table", "jquery", "layer", "laydate"], function () {
            let table = layui.table;
            let $ = layui.jquery;
            let layer = layui.layer;
            let laydate = layui.laydate;
            let select_product_models = [];
            let dynamic_plan_id = "";
            laydate.render({
                elem: "#start_time",
                value: new Date(),
                format: "yyyy-MM-dd",
                type: 'date'
            })
            laydate.render({
                elem: "#end_time",
                value: new Date(),
                format: "yyyy-MM-dd",
                type: 'date'
            })
            tableRender(null);


            // 监听checkbox的点击事件
            table.on('checkbox(show_table)', function (obj) {
                let tr = obj.tr; // 获取当前行
                if (obj.checked) {
                    // 如果checkbox被选中，设置背景色
                    $(tr).css('background-color', 'yellowgreen'); // 根据需要设置选中时的背景色
                } else {
                    // 如果checkbox被取消选中，恢复背景色
                    $(tr).css('background-color', ''); // 恢复默认背景色
                }
            });

            // 监听checkbox的点击事件
            table.on('checkbox(bind_table)', function (obj) {
                let tr = obj.tr; // 获取当前行
                let dt = obj.data;
                let select_product = dt["product_model"]
                let ty = obj.type;
                if (ty === "all" && obj.checked) {
                    //选中所有

                } else if (ty === "all" && !obj.checked) {
                    //取消选中所有
                    select_product_models = [];
                } else if (ty === "one") {
                    if (obj.checked) {
                        // 如果checkbox被选中，设置背景色
                        $(tr).css('background-color', 'orange'); // 根据需要设置选中时的背景色
                        select_product_models[select_product_models.length] = select_product
                    } else {
                        // 如果checkbox被取消选中，恢复背景色
                        $(tr).css('background-color', ''); // 恢复默认背景色
                        let idx = select_product_models.indexOf(select_product);
                        if (idx > -1) {
                            select_product_models.splice(idx, 1);
                        }
                    }
                }
                console.log(select_product_models);
            });

            // 监听checkbox的点击事件
            table.on('checkbox(bind_execute_table)', function (obj) {
                let tr = obj.tr; // 获取当前行
                if (obj.checked) {
                    // 如果checkbox被选中，设置背景色
                    $(tr).css('background-color', 'green'); // 根据需要设置选中时的背景色
                } else {
                    // 如果checkbox被取消选中，恢复背景色
                    $(tr).css('background-color', ''); // 恢复默认背景色
                }
            });

            function tableRender(param) {
                table.render({
                    elem: "#show_table",
                    method: "post",
                    url: "/api/plan/get_plan_list",
                    where: param,
                    page: true,
                    limit: 8,
                    limits: [8, 10, 20, 30],
                    cols: [[
                        {type: 'checkbox', fixed: 'left'},
                        {
                            field: "id",
                            title: "计划编号",
                            width: 100,
                            align: "center",
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        },
                        {
                            field: "plan_name",
                            title: "计划名称",
                            align: "center",
                            width: 120,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        },
                        {
                            field: "plan_type",
                            title: "计划类型",
                            align: "center",
                            width: 250,
                            style: 'background-color:white;color:purple;opacity:0.9;'
                        },
                        {
                            field: "is_finish",
                            title: "计划状态",
                            align: "center",
                            width: 100,
                            style: 'background-color:white;color:blue;opacity:0.9;'
                        },
                        {
                            field: "start_time",
                            title: "计划开始时间",
                            align: "center",
                            width: 150,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        },
                        {
                            field: "end_time",
                            title: "计划结束时间",
                            align: "center",
                            width: 150,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        },
                        {
                            field: "create_time",
                            title: "创建时间",
                            align: "center",
                            width: 120,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        },
                        // {
                        //     field: "log_msg",
                        //     title: "日志信息",
                        //     align: "center",
                        //     width: 400,
                        //     style: 'background-color:white;color:red;opacity:0.9;'
                        // },
                        // {
                        //     field: "log_args",
                        //     title: "日志参数",
                        //     align: "center",
                        //     width: 200,
                        //     style: 'background-color:white;color:purple;opacity:0.9;'
                        // }
                        // ,
                        {
                            title: "操 作",
                            toolbar: "#operator",
                            align: "center",
                            width: 200,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        },
                        {
                            field: "remark",
                            title: "备注信息",
                            align: "center",
                            width: 200,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        }
                    ]]
                    , rowStyle: function (row, index) {
                        // 当前行索引为选中行时的样式
                        if (row.checked === true) {
                            return {css: {'background-color': '#429ff5', 'color': '#fff'}};
                        }
                    }
                })
            }

            function executeTableRender(param) {
                table.render({
                    elem: '#bind_execute_table',
                    method: "post",
                    toolbar: '#toolbarDemo1',
                    url: "/api/plan/get_dynamic_execute_result",
                    where: param,
                    page: true,
                    limit: 8,
                    limits: [8, 10, 20, 30],
                    cols: [[
                        {
                            field: "e_sort",
                            title: "执行顺序",
                            align: "center",
                            width: 180,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        },
                        {
                            field: "product_model",
                            title: "执行型号",
                            align: "center",
                            width: 250,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        },
                        {
                            field: "total",
                            title: "可建造数量",
                            align: "center",
                            width: 200,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        }
                    ]]
                })
            }

            table.on('tool(show_table)', function (obj) {
                let row_data = obj.data;
                let plan_type = row_data["plan_type_code"]
                dynamic_plan_id = row_data["id"]
                if (obj.event === 'del') {
                    let param = {
                        id: row_data["id"]
                    }
                    $.post("/api/plan/del_plan", param, function (res) {
                        if (res.code === 200) {
                            layer.msg(res.msg, {icon: 6, time: 1500}, function () {
                                tableRender(null)
                                //layer.close(idx);
                            })
                        } else {
                            layer.msg(res.msg, {icon: 6, time: 1500}, function () {
                                // tableRender(null)
                            })
                        }
                    })
                }
                if (obj.event === 'execute' && plan_type !== 2) {
                    $.post("/api/plan/execute_plan", {
                        "plan_id": row_data["id"]
                    }, function (res) {
                        if (res.code === 200) {
                            layer.msg(res.msg, {icon: 6, time: 3000}, function () {
                                // tableRender(null)
                            })
                        } else {
                            layer.msg(res.msg, {icon: 2, time: 3000}, function () {
                                // tableRender(null)
                            })
                        }
                    })
                }
                if (obj.event === 'execute' && plan_type === 2) {
                    //每次打开时重置
                    select_product_models = []
                    //动态执行
                    let open_index = layer.open({
                        type: 1,
                        content: $('#dynamic_execute'),
                        title: '动态执行',
                        area: ['1000px', '600px'],
                        btn: ['确定', '取消'],
                        yes: function (index, layerout) {

                        },
                        btn2: function (index, layer) {

                        },
                        success: function () {
                            getProductModel();
                            executeTableRender({"plan_id": dynamic_plan_id});
                            // $.post("/order/get_bind_msg", row_data, function (res) {
                            //     if (res.code === 200) {
                            //
                            //     } else {
                            //         layer.msg(res.msg, {icon: 2, time: 1500}, function () {
                            //             tableRender(null)
                            //         })
                            //     }
                            // })
                        }
                    })
                }
            })

            $("#product_search").click(function () {
                getProductModel({"product_model": $("#product_model_s").val()})
                executeTableRender({"plan_id": dynamic_plan_id})
            })

            // 工具栏事件
            table.on('toolbar(bind_table)', function (obj) {
                let id = obj.config.id;
                let checkStatus = table.checkStatus(id);
                let othis = lay(this);
                switch (obj.event) {
                    case 'executeCheckData':
                        let data = checkStatus.data;
                        let products = ""
                        for (let i = 0; i < data.length; i++) {
                            products += data[i]["product_model"] + ","
                        }
                        let param = {
                            "product_models": products,
                            "plan_id": dynamic_plan_id,
                        }
                        $.post("/api/plan/execute_dynamic_plan", param, function (res) {
                            if (res.code === 200) {
                                layer.msg(res.msg, {icon: 6, time: 1500}, function () {
                                    executeTableRender({"plan_id": dynamic_plan_id});
                                })
                            } else {
                                layer.msg(res.msg, {icon: 2, time: 1500}, function () {
                                    // tableRender(null)
                                })
                            }
                        })
                        // layer.alert(layui.util.escape(JSON.stringify(data)));
                        break;
                    case 'getData':
                        let getData = table.getData(id);
                        layer.alert(layui.util.escape(JSON.stringify(getData)));
                        break;
                }
            });

            function loadingform(message) {
                // loading = parent.layer.load(2, {
                loading = layer.load(2, {
                    shade: [0.3, '#fff'],
                    content: message,
                    success: function (layerContentStyle) { // 设置loading样式
                        layerContentStyle.find('.layui-layer-content').css({
                            'padding-left': '45px',
                            'text-align': 'left',
                            'width': '250px',
                            'line-height': '30px'
                        });
                    }
                })
            }

            function doAjax_FileDownload(url, param, callback) {

                // 构造XMLHttpRequest对象
                let xmlRequest = new XMLHttpRequest();
                // 发送get请求
                xmlRequest.open("POST", url, true);
                // 设置响应类型
                xmlRequest.responseType = "blob";
                // 发送请求
                xmlRequest.send(JSON.stringify(param));

                // 请求获得响应之后,触发下面的回调函数
                xmlRequest.onload = function (oEvent) {
                    // 当时满足下面的状态码的时候,视为下载成功
                    if ((xmlRequest.status >= 200 && xmlRequest.status < 300) || xmlRequest.status === 304) {

                        // 从xmlRequest对象中获取响应的内容
                        let content = xmlRequest.response;

                        /*
                            从xmlRequest的响应头中获取文件名字符串
                            因为我们将文件以流的形式返回前端,返回的文件没有文件名
                            因此在后端处理的时候,我们将文件名放到响应头中
                            然后在前端从响应头中获取文件名
                        */
                        let dispositionStr = xmlRequest.getResponseHeader('content-disposition');
                        if (dispositionStr == null || dispositionStr === "") {
                            alert("下载失败!");
                            return;
                        }

                        // 获取文件名
                        let dispositionArr = dispositionStr.split("=");
                        // 我们的文件名可能含有汉字,因此在后端进行了UTF-8编码处理,此处进行解码
                        let fileName = decodeURIComponent(dispositionArr[1]);

                        // 利用response的响应内容构造一个Blob对象(通过Blob对象进行下载)
                        let blob = new Blob([content]);

                        // 创建一个隐藏的用来下载文件的a标签
                        let elink = document.createElement('a');
                        elink.download = fileName;
                        elink.style.display = 'none';

                        /*
                            将blob文件对象转换为内存中对象,并将生成的对象赋给隐藏的a标签
                            bolb对象会暂时存储在客户端的内存中,
                            使用URL.createObjectURL()方法可以创建指向内存文件对象的临时url
                            使用createObjectURL可以节省性能并更快速,只不过需要在不使用的情况下手动释放内存
                            FileReader.readAsDataURL返回文件的base64字符串，比blob url消耗更多内存，但是在不用的时候会自动从内存中清除（通过垃圾回收机制）
                        */
                        const src = URL.createObjectURL(blob);
                        elink.href = src;
                        document.body.appendChild(elink);

                        // 模拟点击下载事件,进行下载
                        elink.click();

                        // 点击之后,移除我们定义的隐藏a标签
                        document.body.removeChild(elink);

                        // 移除文件对象
                        URL.revokeObjectURL(src)
                    }
                }
            }

            // 工具栏事件
            table.on('toolbar(bind_execute_table)', function (obj) {
                let id = obj.config.id;
                let checkStatus = table.checkStatus(id);
                let othis = lay(this);
                switch (obj.event) {
                    case 'export':
                        let param = {
                            "plan_id": dynamic_plan_id
                        }
                        let idx = layer.confirm('确定要导出结果到excel表格?', function (index) {
                            loadingform('正在生成excel文件,请稍等...')
                            $.post('/api/plan/export_dynamic_result', param, function (res) {
                                let cls = "layui-layer layui-layer-loading"
                                $(".layui-layer").remove()
                                $(".layui-layer-shade").remove()
                                let down_param = {}
                                if (res.code === 200) {
                                    let download_param = {
                                        file_name: res.data.file_name,
                                        export_name: res.data.export_name
                                    }
                                    layer.open({
                                        type: 1
                                        , id: 'layerDemo_export' //防止重复弹出
                                        , content: '<div style="padding: 20px 100px;">' + res.msg + '</div>'
                                        , btn: '下载文件'
                                        , btnAlign: 'c' //按钮居中
                                        , shade: 0 //不显示遮罩
                                        , yes: function () {
                                            doAjax_FileDownload('/api/download/download_file', download_param, null)
                                            layer.closeAll()
                                        }
                                    });
                                } else {
                                    layer.msg(res.msg, {icon: 2, time: 1500})
                                }
                            })
                        });
                        break;
                    case 'getData':
                        let getData = table.getData(id);
                        layer.alert(layui.util.escape(JSON.stringify(getData)));
                        break;
                }
            });

            function getProductModel(row_data) {
                table.render({
                    elem: "#bind_table",
                    method: "post",
                    toolbar: '#toolbarDemo',
                    url: "/api/xh/get_xh_list",
                    where: row_data,
                    page: true,
                    limit: 8,
                    limits: [8, 10, 20, 30],
                    cols: [[
                        {type: 'checkbox', fixed: 'left'},
                        {
                            field: "product_model",
                            title: "型号",
                            align: "center",
                            width: 270,
                            style: 'background-color:white;color:gray;opacity:0.9;'
                        },
                        // {
                        //     field: "product_level",
                        //     title: "型号级别",
                        //     align: "center",
                        //     width: 120,
                        //     style: 'background-color:white;color:gray;opacity:0.9;'
                        // }
                    ]]
                })
            }

            $("#searchconfig").click(function () {
                search_func();
            })

            function search_func() {
                let material_name = $("#material_name").val()
                tableRender({
                    "material_name": material_name
                });
            }

            $('#order_no_search').bind('keypress', function (event) {
                if (event.keyCode === 13) {
                    search_func();
                }
            })

            $("#datainit").click(function () {
                /**
                 // 显示加载层
                 // let loadIndex = layer.load(0, {
                 //     shade: [0.5, '#fff'],
                 //     zIndex: layer.zIndex,
                 //     content: "正在订单校验中...请稍后"
                 // });
                 // 在顶层显示加载层
                 // layer.setTop();
                 // $.post("/order/cal/order_cl", {}, function (res) {
                 //     // layer.close(loadIndex);
                 //     if (res.code === 200) {
                 //         layer.msg(res.msg, {icon: 6, time: 3000}, function () {
                 //             tableRender(null)
                 //         })
                 //     } else {
                 //         layer.msg(res.msg, {icon: 2, time: 3000}, function () {
                 //             // tableRender(null)
                 //         })
                 //     }
                 //
                 // })**/

                let idx = layer.open(
                    {
                        type: 1,
                        content: $('#addplan'),
                        title: '新增计划',
                        area: ['500px', '400px'],
                        btn: ['确定', '取消'],
                        yes: function (index, layerout) {
                            let plan_name = $("#plan_name").val()
                            if (plan_name === undefined || plan_name === "") {
                                layer.msg("计划名称不能为空", {icon: 2, time: 1500}, function () {
                                    //tableRender(null)
                                })
                                return;
                            }
                            let start_time = $("#start_time").val()
                            if (start_time === undefined || start_time === "") {
                                layer.msg("计划开始时间不能为空", {icon: 2, time: 1500}, function () {
                                    //tableRender(null)
                                })
                                return;
                            }
                            let end_time = $("#end_time").val()
                            if (end_time === undefined || end_time === "") {
                                layer.msg("计划结束时间不能为空", {icon: 2, time: 1500}, function () {
                                    //tableRender(null)
                                })
                                return;
                            }
                            let param = {
                                plan_name: plan_name,
                                start_time: start_time,
                                end_time: end_time,
                                plan_type: $("#plan_type").val()
                            }
                            $.post("/api/plan/add_plan", param, function (res) {
                                if (res.code === 200) {
                                    layer.msg(res.msg, {icon: 6, time: 1500}, function () {
                                        tableRender(null)
                                        layer.close(idx);
                                    })
                                } else {
                                    layer.msg(res.msg, {icon: 6, time: 1500}, function () {
                                        // tableRender(null)
                                    })
                                }
                            })
                        },
                        btn2: function (index, layer) {

                        },
                        success: function () {

                        }
                    }
                );
            })
        }
    )
</script>
</html>